(function($, doc) {
	$.plusReady(function() {
		var scan;
		mui.init({
			beforeback: function() {
				closeScan();
			}
		});
		/*
	var height = window.innerHeight + 'px';//获取页面实际高度  
    var width = window.innerWidth + 'px';  
    document.getElementById("bcid").style.height= height;  
    document.getElementById("bcid").style.width= width; 
    console.log(document.getElementById("bcid").offsetWidth);*/
		var userinfo = app.getState();
		var uid = userinfo.user_id;

		// 扩展API加载完毕后调用onPlusReady回调函数 
		//document.addEventListener("plusready", onPlusReady, false);
		var styles = {
			frameColor: "#29E52C",
			scanbarColor: "#29E52C",
			background: ""
		};
		scan = new plus.barcode.Barcode('bcid', styles);
		//scan.close();
		scan.onmarked = onmarked;
		scan.start();

		function onmarked(type, result) {
			var text = '未知: ';
			switch(type) {
				case plus.barcode.QR:
					text = 'QR: ';
					break;
				case plus.barcode.EAN13:
					text = 'EAN13: ';
					break;
				case plus.barcode.EAN8:
					text = 'EAN8: ';
					break;
			}
			//alert(text + result);
			//scan.close();
			parseQrcode(result);
		}

		function parseQrcode(result) {
			var pre = result.substring(0, 2); //是否为钱包地址
			var str = result.replace(/\"/g, "").split('@');
			var type = str[0],
				rt = str[1];
			if(pre == "0x") {
				tocoin(result, 0);
				return;
			}
			//alert(type);
			//if((!type || !rt) && pre != "0x") {
			if(!type || !rt) {
				mui.alert('扫码失败');
				return;
			}
			var player = document.createElement('audio');
			player.src = '../../static/sound/di.mp3';
			player.volume = 1;
			player.loop = false;
			player.play();
			if(type == 'user') {
				touser(rt);
			} else if(type == 'pay') {
				topay(rt);
			} else if(type == 'cash') {
				tocash(rt);
			} else if(type == 'room') {
				toroom(rt);
			} else if(type == 'coin') {
				tocoin(str, 1);
			} else if(type === 'paymerchant') {
				topaymerchant(rt);
			} else {
				toaddress(result);
				//				mui.alert('扫码失败');
				//				return;
			}
		}

		function tocoin(str, type) {
			closeScan();
			if(type < 1) {
				var addr = 'eth';
				var name = 'ETH';
				var outaddr = str;
			} else {
				var addr = str[2];
				var name = str[3];
				var outaddr = str[1];
			}
			plus.webview.close('coindetail', 'none');
			$.openWindow({
				url: '../../pages/coin/coindetail.html',
				id: 'coindetail',
				extras: {
					address: addr,
					name: name,
					outaddr: outaddr
				}
			})
		}

		function touser(rt) {
			closeScan();
			var targets = '/pages/user/other_detail.html';
			mui.openWindow({
				url: targets,
				id: targets,
				extras: {
					fid: rt
				}
			});
		}

		function topay(rt) {
			closeScan();
			var postUrl = apiurl + "wallet/getWallets";
			var postdata = {
				from_id: rt,
				to_id: uid
			};

			$.post(postUrl, postdata, function(res) {
				if(res.status == 1) {
					var f = res.data.from;
					var t = res.data.to;
					var url = "../../pages/wallet/sendTxEmb.html?fromtype=1&id=" + f['id'] + "&name=" + f['name'] + "&pubkey=" + f.pubkey + "&type=" + f.type + "&tokens=" + f.tokens + "&isdefault=1&user_id=" + uid + "&to=" + t.address;
					mui.openWindow({
						url: url,
						id: 'pages/chat/transfer_accounts',
						extras: {
							roomId: uid
						}
					});
				} else {
					mui.alert(res.msg);
				}
			});
		}

		function toroom(rt) {
			closeScan();
			var postUrl = apiurl + "chat/joinRoom";
			var postdata = {
				user_id: uid,
				room_id: rt
			};

			$.post(postUrl, postdata, function(res) {
				if(res.status == 2) {
					var room = res.room;
					mui.openWindow({
						url: '/pages/chat/chat_index.html',
						id: 'chatbox',

						show: {
							autoShow: true,
							aniShow: 'slide-in-right',
							duration: 100
						},
						extras: {
							chatTitle: room.name,
							chatHeader: room.avatar,
							roomId: room.user_id,
							roomType: 2
						}
					});
				} else {
					mui.alert(res.msg);
				}
			});
		}

		function tocash(rt) {
			closeScan();
			var postUrl = apiurl + "wallet/getWallets";
			var postdata = {
				from_id: uid,
				to_id: rt
			};

			$.post(postUrl, postdata, function(res) {
				if(res.status == 1) {
					var f = res.data.from;
					var t = res.data.to;
					var url = "../../pages/wallet/sendTxEmb.html?fromtype=1&id=" + f['id'] + "&name=" + f['name'] + "&pubkey=" + f.pubkey + "&type=" + f.type + "&tokens=" + f.tokens + "&isdefault=1&user_id=" + uid + "&to=" + t.address;
					mui.openWindow({
						url: url,
						id: 'pages/chat/transfer_accounts',
						extras: {
							roomId: rt
						}
					});
				} else {
					mui.alert(res.msg);
				}
			});
		}

		function toaddress(result) {
			closeScan();
			var targetWnd = plus.webview.currentWebview().opener();
			$.fire(targetWnd, 'scanaddress', {
				result: result
			});
			plus.webview.currentWebview().close();
		}

		function topaymerchant(rt) {

			var items = rt.split('|');
			var message = '您确定要向商户' +
				decodeURIComponent(items[3]) +
				'支付【' + items[2] + '】' +
				decodeURIComponent(items[1]) + '吗？';

			closeScan();

			mui.confirm(message, ['确定', '取消'], function(e) {

				if(e.index === 0) {
					dopaymerchant(items[0], items[2]);
				} else {
					mui.back();
				}
			});
		}

		function dopaymerchant(id, price) {
			//console.log(appurl + 'chatapi/getsms');
			mui.post(appurl + 'ChatApi/getsms', {
				u: app.getState().user_id,
				smstype: 9
			}, function(res) {
				//console.log(JSON.stringify(res));
				if(res.status == 1) {
					mui.toast('发送短信成功');
					var input = mui.prompt('请输入短信验证码', '', '', ['确定', '取消'], function(e) {

						if(e.index === 0) {
							var pwd = e.value;

							if(pwd && pwd.length > 0) {

								$.post(weburl + 'ChatApi/ajaxPayMerchant', {
									u: uid,
									code: pwd,
									smstype : 9,
									order_id: id,
									price: price

								}, function(res) {

									if(res.status === 1) {
										mui.alert('支付成功！');
										mui.back();
									} else {
										//dopaymerchant(id);
										mui.alert(res.msg);
									}
								});

							} else {
								//dopaymerchant(id);
								$.toast('密码不能为空！');
							}
						} else {
							mui.back();
						}

					}, 'div').element.querySelector('input');
					/*
					if(input) {
						input.type = 'password';
						input.focus();
					}*/
				} else {
					mui.toast(res.msg);
					return;
				}

			});

		}

		function cancelScan() {
			scan.cancel();
		}

		function onPlusReady() {

			/*
			varself = plus.webview.currentWebview();
			varopener = self.opener();
			//scan.cancel();
			mui.fire(opener, 'endScan', {
				result: result,
				file: file
			});*/
		}

		function startRecognize() {
			scan = new plus.barcode.Barcode('bcid');
			scan.onmarked = onmarked;
		}

		function startScan() {
			scan.start();
		}

		function closeScan() {
			scan.cancel();
			scan.close();
		}
		// 从相册中选择二维码图片 
		function scanPicture() {
			plus.gallery.pick(function(path) {
				plus.barcode.scan(path, onmarked, function(error) {
					plus.nativeUI.alert("无法识别此图片");
				});
			}, function(err) {
				plus.nativeUI.alert("Failed: " + err.message);
			});
		}
		mui(".footer").on("tap", "#pic", function() {
			//scan.close();
			//scan.start();
			scanPicture();
		});
		$.back = function(event) {
			closeScan();
			plus.webview.currentWebview().close();
			//location.href = '../../find.html';
			//plus.webview.show('me.html', "slide-in-right", 300);
			return false;
		};
	});

}(mui, document));